import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '../types'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)

  // 从 localStorage 恢复登录状态
  const initializeFromStorage = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    if (username === 'admin' && password === 'admin') {
      user.value = {
        id: 1,
        username: 'admin',
        role: 'admin'
      }
      
      // 保存到 localStorage
      localStorage.setItem('user', JSON.stringify(user.value))
      return true
    }
    
    throw new Error('用户名或密码错误')
  }

  // 登出
  const logout = () => {
    user.value = null
    localStorage.removeItem('user')
  }

  const isLoggedIn = computed(() => !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  return {
    user,
    login,
    logout,
    isLoggedIn,
    isAdmin,
    initializeFromStorage
  }
}) 